<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2019/9/18
 * Time: 14:41
 */
namespace app\api\controller;
use think\Db;
use org\Qiniu;
class Timing extends Base
{
    public $startMonth; // 开始月份
    public $endMonth; // 结束月份
    public $limitMonth; // 限制数量

    //*******************************************************  关闭订单  start
    /**
     * 将30分钟未付款的订单设置成关闭----特惠商品订单
     * 每分钟跑
     */
    public function orderOverTime(){
        // 30分钟前时间
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));
        // 未付款订单
        $order = Db::table('up_order')
            ->where('order_status', 1)
            ->where('order_is_pay', 1)
            ->where('order_del', 1)
            ->whereTime('order_create_time', '<', $time)
            ->field('order_id')
            ->select();
        if($order){
            Db::startTrans();
            try{
                foreach($order as $k => $v){
                    // 修改状态
                    Db::table('up_order')->where('order_id', $v['order_id'])->update(['order_status' => 5, 'order_close_time' => date('Y-m-d H:i:s')]);
    
                    $order_goods = Db::table('up_order_info')->where('oi_order_id', $v['order_id'])->field('oi_goods_id, oi_num')->select();
                    foreach($order_goods as $kk => $vv){
                        // 释放库存
                        Db::table('up_goods')->where('goods_id', $vv['oi_goods_id'])->setInc('goods_stock', $vv['oi_num']);
                        // 减销量
                        Db::table('up_goods')->where('goods_id', $vv['oi_goods_id'])->setDec('goods_sale_num', $vv['oi_num']);
                    }
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 将30分钟未付款的订单设置成关闭----统一商品
     * 每分钟跑
     */
    public function boOrderOverTime(){
        // 30分钟前时间
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));
        
        $order_ids = Db::table('up_bo_order')
            ->where('bo_status', 1)
            ->whereTime('bo_create_time', '<', $time)
            ->column('bo_id');
        if($order_ids){
            
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_bo_order')->where('bo_id', 'IN', $order_ids)->update([
                    'bo_status' => 5,
                    'bo_close_time' => date('Y-m-d H:i:s')
                ]);
                
                // 释放库存&减销量
                $goods = Db::table('up_bo_order_info')
                    ->join('up_bo_goods', 'bg_id = boi_goods_id', 'LEFT')
                    ->where('boi_order_id', 'IN', $order_ids)
                    ->field('boi_goods_id, boi_goods_number, bg_sale_number, bg_stock')
                    ->select();
                foreach($goods as $k => $v){
                    Db::table('up_bo_goods')->where('bg_id', $v['boi_goods_id'])->update([
                        'bg_id' => $v['boi_goods_id'],
                        'bg_stock' => $v['bg_stock'] + $v['boi_goods_number'],
                        'bg_sale_number' => $v['bg_sale_number'] - $v['boi_goods_number']
                    ]);
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    
    /**
     * 将30分钟未付款的订单设置成关闭----礼包订单
     * 每分钟跑
     */
    public function giftOrderOverTime(){
        // 30分钟前时间
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));
        
        $bog_id = Db::table('up_bo_orderg')
            ->where('bog_status', 1)
            ->whereTime('bog_create_time', '<', $time)
            ->column('bog_id');
        if($bog_id){
            // 修改订单状态
            Db::table('up_bo_orderg')->where('bog_id', 'IN', $bog_id)
                ->update([
                    'bog_status' => 5,
                    'bog_close_time' => date('Y-m-d H:i:s')
                ]);
        }
    }

    /**
     * 将30分钟未付款的订单设置成关闭----家大业大
     * 每分钟跑
     */
    public function bigOrderOverTime(){
        // 30分钟前时间
        $time = date('Y-m-d H:i:s', strtotime('-30 minute'));

        $order_ids = Db::table('up_big_order')
            ->where('bo_is_pay', 1)
            ->whereTime('bo_create_time', '<', $time)
            ->column('bo_id');
        if($order_ids){

            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_big_order')->where('bo_id', 'IN', $order_ids)->update([
                    'bo_status' => 5,
                    'bo_close_time' => date('Y-m-d H:i:s')
                ]);

                // 释放库存&减销量
                $goods = Db::table('up_big_order_info')
                    ->join('up_big_goods', 'goods_id = boi_goods_id', 'LEFT')
                    ->where('boi_order_id', 'IN', $order_ids)
                    ->field('boi_goods_id, boi_goods_number')
                    ->select();
                foreach($goods as $k => $v){
                    Db::table('up_big_goods')->where('goods_id', $v['boi_goods_id'])
                        ->inc('goods_stock', $v['boi_goods_number'])
                        ->dec('goods_sale_num', $v['boi_goods_number'])
                        ->update();
                }
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
            }
        }
    }
    //*******************************************************  关闭订单  end
    
    //*******************************************************  确认收货  start
    /**
     * 超过两个星期没有确认收货的，要自动确认收货----特惠商品订单
     * 每天凌晨跑
     */
    public function orderAffirm(){
        // 两周前
        $two_week = date('Y-m-d H:i:s', strtotime('-2 weeks'));
        Db::table('up_order')
            ->where('order_status', 3)
            ->where('order_del', 1)
            ->whereTime('order_send_time', '<', $two_week)
            ->update([
                'order_status' => 4,
                'order_over_time' => date('Y-m-d H:i:s')
            ]);
        
    }

    /**
     * 超过两个星期没有确认收货的，要自动确认收货----统一商品订单
     * 每天凌晨跑
     * 这是没有分佣的版本，目前先用这个版本
     */
    public function boOrderAffirm(){
        // 两周前
        $two_week = date('Y-m-d H:i:s', strtotime('-2 weeks'));
        Db::table('up_bo_order')
            ->where('bo_status', 3)
            ->whereTime('bo_send_time', '<', $two_week)
            ->update([
                'bo_status' => 4,
                'bo_over_time' => date('Y-m-d H:i:s')
            ]);
    }
    
    /**
     * 超过两个星期没有确认收货的，要自动确认收货----礼包订单
     * 每天凌晨跑
     */
    public function giftOrderAffirm(){
        // 两周前
        $two_week = date('Y-m-d H:i:s', strtotime('-2 weeks'));
        Db::table('up_bo_orderg')
            ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
            ->where('bog_status', 3)
            ->whereTime('bog_send_time', '<', $two_week)
            ->update([
                'bog_status' => 4,
                'bog_over_time' => date('Y-m-d H:i:s'),
                'bog_get_way' => '系统自动确认收货'
            ]);
    }


    /**
     * 超过两个星期没有确认收货的，要自动确认收货----家大业大订单
     * 每天凌晨跑
     */
    public function bigOrderAffirm(){
        // 两周前
        $two_week = date('Y-m-d H:i:s', strtotime('-2 weeks'));
        Db::table('up_big_order')
            ->where('bo_status', 3)
            ->whereTime('bo_send_time', '<', $two_week)
            ->update([
                'bo_status' => 4,
                'bo_over_time' => date('Y-m-d H:i:s')
            ]);

    }
    
    //*******************************************************  确认收货  end
    
    /**
     * 减上月礼包有效期和可领面膜数
     * 每月凌晨跑
     * 没有领取记录-1，上个月在领取总数覆盖月份之外-1
     */
    public function decIndate(){
        $dateTime = date('Y-m-01 00:00:00');
        $data = Db::table('up_bo_orderg')
            ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
            ->where('bog_is_pay', 2)
            ->where('bog_indate_month', '>', 0)
            ->where('bog_pay_time', '<', $dateTime)
            ->field('bog_id, bog_indate_month, bog_zeng_number, bog_pay_time, user_giftbag_store_time, bog_pay_month')
            ->select();
        $passTimeStr = strtotime("last day of -1 month");
        $passMonth = date('Y-m', $passTimeStr); // 上个月
        if($data){
            foreach ($data as $ke => $v){
                $update = [];
                $alreadyGet = Db::table('up_bo_orderz')
                    ->where(['boz_order_id' => $v['bog_id'], 'boz_is_pay' => 2])
                    ->field('boz_id, boz_no, boz_pay_time')
                    ->order('boz_pay_time asc')
                    ->select();
                $update['bog_id'] = $v['bog_id'];
                $update['bog_indate_month'] = $v['bog_indate_month'] - 1;
                if($alreadyGet){
                    $end_arr = end($alreadyGet);
                    $payMonthZ = date('Y-m', strtotime($end_arr['boz_pay_time'])); // 最后一次领取月份

                    if($payMonthZ == $passMonth){ // 如果上个月领了，则不扣数量

                    }else{
                        $last_boz_id = $end_arr['boz_id']; // 最后一个数组元素的id
                        $this->startMonth = date('Y-m', strtotime($alreadyGet[0]['boz_pay_time']));
                        $this->limitMonth = $alreadyGet[0]['boz_no'];
                        foreach ($alreadyGet as $kk => $vv){
                            if($vv['boz_id'] < $last_boz_id){ // 如果不是最后一个数组
                                $endMonth = date('Y-m', strtotime("last day of +{$this->limitMonth} month", strtotime($this->startMonth)));
                                $nextMonth = date('Y-m', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                                if($nextMonth <= $endMonth){
                                    $this->limitMonth = $this->limitMonth + $alreadyGet[$kk + 1]['boz_no'];
                                }else{
                                    $this->startMonth = date('Y-m', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                                    $this->limitMonth = $alreadyGet[$kk + 1]['boz_no'];
                                }
                            }
                        }
                        if($this->limitMonth == 1){ // 只领了一盒，并且不是上个月领取的，要减1
                            if($v['bog_zeng_number'] != 0){
                                $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                            }
                        }else{
                            $this->endMonth = date('Y-m', strtotime("last day of +{$this->limitMonth} month", strtotime($this->startMonth)));
                            if($passMonth >= $this->endMonth){
                                if($v['bog_zeng_number'] != 0){
                                    $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                                }
                            }
                        }
                    }
                }else{
                    // 如果没有领取记录，则需要判断是不是上个月购买的，或者是上个月加入会员的，如果是，则不扣
                    if($v['user_giftbag_store_time']){
                        // 如果礼包订单付款日期小于入会日期，则以入会日期判断，反之以付款日期判断
                        $joinDate = date('Y-m', strtotime($v['user_giftbag_store_time']));
                        if($v['bog_pay_month'] < $joinDate){
                            $checkDate = $joinDate;
                        }else{
                            $checkDate = $v['bog_pay_month'];
                        }
                    }else{
                        $checkDate = $v['bog_pay_month'];
                    }
                    if($checkDate != $passMonth){
                        if($v['bog_zeng_number'] != 0){
                            $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                        }
                    }
                }

                Db::table('up_bo_orderg')->update($update);
                if(isset($update['bog_zeng_number'])){
                    $mm_number = 1;
                }else{
                    $mm_number = 0;
                }
                insertGiftbagLog($v['bog_id'], '系统自动扣除', 1, $mm_number);
            }
        }
    }

    /**
     * 手动跑
     * 测试用
     */
    public function decIndate1(){
        $dateTime = date('Y-m-d H:i:00');
        $data = Db::table('up_bo_orderg')
            ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
            ->where('bog_is_pay', 2)
            ->where('bog_indate_month', '<>', 0)
            ->where('bog_pay_time', '<', $dateTime)
            ->field('bog_id, bog_indate_month, bog_zeng_number, bog_pay_time, user_giftbag_store_time, bog_pay_month')
            ->select();
        $passMonth = date('Y-m-d H:i:00', strtotime("-30 minutes")); // 上个小时
        if($data){
//            $update = [];
            foreach ($data as $ke => $v){
                $update = [];
                $alreadyGet = Db::table('up_bo_orderz')
                    ->where(['boz_order_id' => $v['bog_id'], 'boz_is_pay' => 2, 'boz_pay_time' => ['<', $dateTime]])
                    ->field('boz_id, boz_no, boz_pay_time')
                    ->order('boz_pay_time asc')
                    ->select();
//                    $update[$ke]['bog_indate_month'] = $v['bog_indate_month'] - 1;
//                    $update[$ke]['bog_id'] = $v['bog_id'];
                $update['bog_id'] = $v['bog_id'];
                $update['bog_indate_month'] = $v['bog_indate_month'] - 1;

                if($alreadyGet){
                    $end_arr = end($alreadyGet);
                    $payMonthZ = date('Y-m-d H:i:00', strtotime($end_arr['boz_pay_time'])); // 最后一次领取月份
                    if($payMonthZ == $passMonth){ // 如果上个月领了，则不扣数量

                    }else{
                        $last_boz_id = $end_arr['boz_id']; // 最后一个数组元素的id
                        $this->startMonth = date('Y-m-d H:i:00', strtotime($alreadyGet[0]['boz_pay_time']));
                        $this->limitMonth = $alreadyGet[0]['boz_no'];
                        foreach ($alreadyGet as $kk => $vv){
                            if($vv['boz_id'] < $last_boz_id){ // 如果不是最后一个数组
                                $limitMonth = $this->limitMonth * 60;
                                $endMonth = date('Y-m-d H:i:00', strtotime("+{$limitMonth} minutes", strtotime($this->startMonth)));
                                $nextMonth = date('Y-m-d H:i:00', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                                if($nextMonth <= $endMonth){
                                    $this->limitMonth = $this->limitMonth + $alreadyGet[$kk + 1]['boz_no'];
                                }else{
                                    $this->startMonth = date('Y-m-d H:i:00', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                                    $this->limitMonth = $alreadyGet[$kk + 1]['boz_no'];
                                }
                            }
                        }
                        if($this->limitMonth == 1){ // 只领了一盒，并且不是上个月领取的，要减1
                            if($v['bog_zeng_number'] != 0){
//                                    $update[$ke]['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                                $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                            }
                        }else{
                            $limitMonth1 = $this->limitMonth * 60;
                            $this->endMonth = date('Y-m-d H:i:00', strtotime("+{$limitMonth1} minutes", strtotime($this->startMonth)));
                            if($passMonth >= $this->endMonth){
                                if($v['bog_zeng_number'] != 0){
//                                        $update[$ke]['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                                    $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                                }
                            }
                        }
                    }
                }else{
                    // 如果没有领取记录，则需要判断是不是上个月购买的，或者是上个月加入会员的，如果是，则不扣
                    if($v['user_giftbag_store_time']){
                        // 如果礼包订单付款日期小于入会日期，则以入会日期判断，反之以付款日期判断
                        $joinDate = date('Y-m', strtotime($v['user_giftbag_store_time']));
                        if($v['bog_pay_month'] < $joinDate){
                            $checkDate = $joinDate;
                        }else{
                            $checkDate = $v['bog_pay_month'];
                        }
                    }else{
                        $checkDate = $v['bog_pay_month'];
                    }
                    if($checkDate != $passMonth){
                        if($v['bog_zeng_number'] != 0){
//                            $update[$ke]['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                            $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                        }
                    }
                }
//print_r($update);die;
                Db::table('up_bo_orderg')->update($update);

            }
//            if($update){
//                foreach ($update as $ku => $vu){
//                    Db::table('up_bo_orderg')->update($vu);
//                }
//            }
//            print_r($update);die;
        }
    }

    /**
     * 手动跑
     * 测试用
     */
    public function decIndate2(){
        $dateTime = date('Y-m');
        $bog_id = 1;
        $data = Db::table('up_bo_orderg')
            ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
            ->where('bog_id', $bog_id)
            ->field('bog_id, bog_indate_month, bog_zeng_number, bog_pay_time, user_giftbag_store_time, bog_pay_month')
            ->find();
        $passMonth = date('Y-m', strtotime("-1 month")); // 上个小时
        $alreadyGet = Db::table('up_bo_orderz')
            ->where(['boz_order_id' => $bog_id, 'boz_is_pay' => 2, 'boz_pay_time' => ['<', $dateTime]])
            ->field('boz_id, boz_no, boz_pay_time')
            ->order('boz_pay_time asc')
            ->select();
        $update['bog_indate_month'] = $data['bog_indate_month'] - 1;
        $update['bog_id'] = $data['bog_id'];
//                    $update['bog_id'] = $v['bog_id'];
//                    $update['bog_indate_month'] = $v['bog_indate_month'] - 1;

        if($alreadyGet){
            $end_arr = end($alreadyGet);
            $payMonthZ = date('Y-m', strtotime($end_arr['boz_pay_time'])); // 最后一次领取月份

            if($payMonthZ == $passMonth){ // 如果上个月领了，则不扣数量

            }else{
                $last_boz_id = $end_arr['boz_id']; // 最后一个数组元素的id
                $this->startMonth = date('Y-m', strtotime($alreadyGet[0]['boz_pay_time']));
                $this->limitMonth = $alreadyGet[0]['boz_no'];
                foreach ($alreadyGet as $kk => $vv){
                    if($vv['boz_id'] < $last_boz_id){ // 如果不是最后一个数组
                        $endMonth = date('Y-m', strtotime("+{$this->limitMonth} months", strtotime($this->startMonth)));
                        $nextMonth = date('Y-m', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                        if($nextMonth <= $endMonth){
                            $this->limitMonth = $this->limitMonth + $alreadyGet[$kk + 1]['boz_no'];
                        }else{
                            $this->startMonth = date('Y-m', strtotime($alreadyGet[$kk + 1]['boz_pay_time']));
                            $this->limitMonth = $alreadyGet[$kk + 1]['boz_no'];
                        }
                    }
                }
                if($this->limitMonth == 1){ // 只领了一盒，并且不是上个月领取的，要减1
                    if($data['bog_zeng_number'] != 0){
                        $update['bog_zeng_number'] = $data['bog_zeng_number'] - 1;
//                                    $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                    }
                }else{
                    $this->endMonth = date('Y-m', strtotime("+{$this->limitMonth} months", strtotime($this->startMonth)));
//                    print_r($this->startMonth . '---' . $this->limitMonth . '---' . $this->endMonth . '---' . $passMonth);
                    if($passMonth >= $this->endMonth){
                        if($data['bog_zeng_number'] != 0){
                            $update['bog_zeng_number'] = $data['bog_zeng_number'] - 1;
//                                        $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                        }
                    }
                }
            }
        }else{
//            print_r(11111);
            // 如果没有领取记录，则需要判断是不是上个月购买的，或者是上个月加入会员的，如果是，则不扣
            if($data['user_giftbag_store_time']){
                // 如果礼包订单付款日期小于入会日期，则以入会日期判断，反之以付款日期判断
                $joinDate = date('Y-m', strtotime($data['user_giftbag_store_time']));
                if($data['bog_pay_month'] < $joinDate){
                    $checkDate = $joinDate;
                }else{
                    $checkDate = $data['bog_pay_month'];
                }
            }else{
                $checkDate = $data['bog_pay_month'];
            }
            if($checkDate != $passMonth){
                if($data['bog_zeng_number'] != 0){
                    $update['bog_zeng_number'] = $data['bog_zeng_number'] - 1;
//                            $update['bog_zeng_number'] = $v['bog_zeng_number'] - 1;
                }
            }
        }
//print_r($update);
//                    Db::table('up_bo_orderg')->update($update);
    }
    
    /**
     * 每月28号凌晨跑，可以多跑两次
     * 将所有小于今天的，可以申请转货款的，通过或者拒绝的提现记录，修改成不可申请部分转货款状态
     */
    /*
    public function chooseZhuan(){
        $time = date('Y-m-28 00:00:00');
        Db::table('up_withdraw')
            ->where([
                'withdraw_time' => ['<', $time],
                'withdraw_type' => 1,
                'withdraw_can_zhuan' => 1,
                'withdraw_status' => 2
            ])
            ->setField('withdraw_can_zhuan', 2);
    }
    */
    
    /**
     * 下载
     */
    public function dowload() {
        /**
         * 平台下载链接
         * 小米：http://app.xiaomi.com/detail/1375163
        */
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo "<script> location.href='https://apps.apple.com/cn/app/%E7%82%B9%E5%8D%B3%E4%B8%BD/id1568240203'; </script>";
        }else{
//            echo "<script> location.href='https://a.app.qq.com/o/simple.jsp?pkgname=com.paixun.fz'; </script>";
            // 服务器下载
            echo "<script> location.href='http://baobei.djlwlsc.com/djlwlsc.apk'; </script>";
        }
        
    }

}